﻿namespace ELF.Gateway;

public class RequestResponseLoggingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<RequestResponseLoggingMiddleware> _logger;

    public RequestResponseLoggingMiddleware(RequestDelegate next, ILogger<RequestResponseLoggingMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        // 记录请求信息
        _logger.LogInformation($"Request: {context.Request.Method} {context.Request.Path}");

        // 记录请求体（如果有）
        if (context.Request.Body != null)
        {
            context.Request.EnableBuffering();
            var requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
            context.Request.Body.Position = 0;
            _logger.LogInformation($"Request Body: {requestBody}");
        }

        // 复制原始响应流以便我们可以读取它
        var originalBodyStream = context.Response.Body;
        using var responseBody = new MemoryStream();
        context.Response.Body = responseBody;

        await _next(context);

        // 记录响应信息
        _logger.LogInformation($"Response Status: {context.Response.StatusCode}");

        // 记录响应体
        responseBody.Seek(0, SeekOrigin.Begin);
        var responseBodyText = await new StreamReader(responseBody).ReadToEndAsync();
        _logger.LogInformation($"Response Body: {responseBodyText}");

        responseBody.Seek(0, SeekOrigin.Begin);
        await responseBody.CopyToAsync(originalBodyStream);
    }
}
